package cn.wen.controller;

import cn.wen.common.enums.HttpCode;
import cn.wen.common.enums.OrderStatus;
import cn.wen.common.utils.PageUtils;
import cn.wen.common.utils.ResultEntity;
import cn.wen.entity.AddressEntity;
import cn.wen.entity.GoodsEntity;
import cn.wen.entity.OrderEntity;
import cn.wen.entity.UserEntity;
import cn.wen.service.AddressService;
import cn.wen.service.GoodsService;
import cn.wen.service.OrderService;
import cn.wen.service.UserService;
import cn.wen.vo.GoodsOrderVO;
import cn.wen.vo.QueryVO;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.CORBA.ORB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**

 * @author yaling
 * @email 932043654
 * @date 2022-08-01 21:52:40
 */
@RestController
@RequestMapping("web")
public class  OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private AddressService addressService;

    /**
     * 获取全部的订单
     */
    @GetMapping("/order/buyer-list")
    public ResultEntity list(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, 0);
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单 （待支付的订单）
     */
    @GetMapping("/order/buyer-list/wait-pay")
    public ResultEntity listPay(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, OrderStatus.WAIT_PAY.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单  待发货（买家）
     */
    @GetMapping("/order/buyer-list/wait-delivery")
    public ResultEntity listDelivery(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, OrderStatus.WAIT_DELIVER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单 待接收
     */
    @GetMapping("/order/buyer-list/wait-receive")
    public ResultEntity listReceive(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, OrderStatus.WAIT_RECEIVE.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单（已完成）
     */
    @GetMapping("/order/buyer-list/finish-order")
    public ResultEntity listFinal(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, OrderStatus.FINISH_ORDER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单  退换/售后
     */
    @GetMapping("/order/buyer-list/cancel-order")
    public ResultEntity listCancel(@RequestParam("userId") String userId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserId(userId, OrderStatus.CANCEL_ORDER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 模糊查询订单
     */
    @GetMapping("/order/buyer-like-list")
    public ResultEntity likeListCancel(@RequestBody QueryVO queryVO,@RequestParam("orderStatus") Integer orderStatus){
        List<GoodsOrderVO> list = orderService.getOrderLikeListByUserId(queryVO, orderStatus);
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 取消订单相当于删除订单记录
     */
    @PostMapping("/order/cancel-order")
    public ResultEntity cancelOrder(@RequestParam("orderId") String orderId){
        boolean result = orderService.cancelOrderByOrderId(orderId);
        if (!result) {
            return ResultEntity.error(500, "取消订单失败！");
        }
        return ResultEntity.ok();
    }

    /**
     * 确认订单状态
     */
    @GetMapping("/order/confirm-order")
    public ResultEntity confirmOrder(@RequestParam("orderId") String orderId){
        boolean result = orderService.confirmOrderByOrderId(orderId);
        if (!result) {
            return ResultEntity.error(500, "确认收货失败！");
        }
        return ResultEntity.ok();
    }


    /**
     * 获取全部的订单 （卖家获取买家待支付的订单列表）
     */
    @GetMapping("/order/seller-list/wait-pay")
    public ResultEntity sellerListPay(@RequestParam("userStoreId") String userStoreId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserStoreId(userStoreId, OrderStatus.WAIT_PAY.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单  待发货（卖家）
     */
    @GetMapping("/order/seller-list/wait-delivery")
    public ResultEntity sellerListDelivery(@RequestParam("userStoreId") String userStoreId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserStoreId(userStoreId, OrderStatus.WAIT_DELIVER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单 （等待买家接受）
     */
    @GetMapping("/order/seller-list/wait-receive")
    public ResultEntity sellerListReceive(@RequestParam("userStoreId") String userStoreId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserStoreId(userStoreId, OrderStatus.WAIT_RECEIVE.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单 （已经完成的订单）
     */
    @GetMapping("/order/seller-list/finish-order")
    public ResultEntity sellerListFinal(@RequestParam("userStoreId") String userStoreId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserStoreId(userStoreId, OrderStatus.FINISH_ORDER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 获取全部的订单  退换/售后（需要退换的订单）
     */
    @GetMapping("/order/seller-list/cancel-order")
    public ResultEntity sellerListCancel(@RequestParam("userStoreId") String userStoreId){
        List<GoodsOrderVO> list = orderService.getOrderListByUserStoreId(userStoreId, OrderStatus.CANCEL_ORDER.getStatus());
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 模糊查询订单    （卖家 全部的模糊查询）
     */
    @GetMapping("/order/seller-like-list")
    public ResultEntity sellerLikeListCancel(@RequestBody QueryVO queryVO,@RequestParam("orderStatus") Integer orderStatus){
        List<GoodsOrderVO> list = orderService.getOrderLikeListByUserStoreId(queryVO, orderStatus);
        return ResultEntity.ok().put("data", list);
    }

    /**
     * 立即购买  创建一个订单
     * 1、订单基本信息
     * 2、订单状态设置为待支付
     * 3、填写订单的一些基本信息  除了地址之类的
     * 创建了一个订单  同时需要返回当前订单的数据
     * @param userId
     * @param goodsId
     * @return
     */
    @PostMapping("/order/place-an-order")
    public ResultEntity placeAnOrder(@RequestParam("userId") String userId, @RequestParam("goodsId") Integer goodsId){
        OrderEntity orderEntity = new OrderEntity();
        // 1、获取购买用户信息
        UserEntity buyerUser = userService.getById(userId);
        // 2、填写物品的基本信息
        GoodsEntity goodsEntity = goodsService.getGoodsBaseInfoByGoodsId(goodsId);
        // 3、获取出售方信息
        UserEntity sellerUser = userService.getById(goodsEntity.getGoodsUserId());
        // 4、填写订单的基本信息
        orderEntity.setOrderId("654" + System.currentTimeMillis());
        orderEntity.setOrderStatus(OrderStatus.WAIT_PAY.getStatus());
        orderEntity.setCreateTime(new Date());
        orderEntity.setGoodsId(goodsId);
        orderEntity.setGoodsNum(1);
        orderEntity.setIsPayed(0);
        orderEntity.setUserShopId(sellerUser.getUserId());
        orderEntity.setUserId(buyerUser.getUserId());
        orderEntity.setTotalPrice(goodsEntity.getGoodsSecondPrice());
        // 创建一个订单
        orderService.placeAnOrder(orderEntity);
        // 返回订单数据  同时需要返回当前用户的地址列表、物品的数据
        List<AddressEntity> userAddressList = addressService.getUserAddressByUserId(userId);
        // TODO 需要实现定时任务删除
        /**
         * 将当前订单id存入redis中  15分钟后查询是否存在 存在则将订单删除  不存在说明提前处理了
         */
        return ResultEntity.ok()
                .put("orderInfo", orderEntity)
                .put("addressList", userAddressList)
                .put("goodsInfo", goodsEntity);
    }

    /**
     * 提交订单  相当于修改订单数据
     *
     * @return
     */
    @PostMapping("/order/submit-order")
    public ResultEntity submitOrder(@RequestBody OrderEntity orderEntity){
        if (orderEntity.getOrderType() == 1) orderEntity.setDvyAmount(0.0);
        orderEntity.setUpdateTime(new Date());
        orderEntity.setOrderStatus(1);
        boolean result = orderService.updateOrder(orderEntity);
        if (!result) return ResultEntity.error(HttpCode.内部服务器错误.getCode(), "提交订单失败！");
        return ResultEntity.ok();
    }

    /**
     * 支付订单
     * @return
     */
    @PostMapping("/order/pay-order")
    public ResultEntity payOrder(@RequestParam("orderId") String orderId){
        boolean result = orderService.updateOrderById(orderId);
        if (!result) return ResultEntity.error(HttpCode.内部服务器错误.getCode(), "支付订单失败！");
        return ResultEntity.ok();
    }

    /**
     * 通过订单编号获取订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/order/query-order")
    public ResultEntity getOrderByOrderId(@RequestParam("orderId") String orderId) {
        GoodsOrderVO orderVO = orderService.getOrderInfoByOrderId(orderId);
        return ResultEntity.ok().put("orderInfo", orderVO);
    }


    /**
     * 获取当前店铺正在转让的物品
     * 还未支付状态、已支付还未发货状态、发货还未接收状态
     * @return
     */
    @GetMapping("/order/seller/on-sold")
    public ResultEntity listStoreGoods(@RequestParam("userStoreId") String userStoreId) {
        // 通过商铺id来获取订单的数据
        List<GoodsOrderVO> list = orderService.selectOrderOnSoldByUserStoreId(userStoreId);
        return ResultEntity.ok().put("orderList", list);
    }

    /**
     * 确认发货
     * @param orderEntity
     * @return
     */
    @PostMapping("/order/seller/submit-deliver")
    public ResultEntity submitDeliver(@RequestBody OrderEntity orderEntity) {
        // 确认发货主要是修改  订单方式、快递单号 可以为空 的
        // 修改发货时间
        orderEntity.setUpdateTime(new Date());
        orderEntity.setOrderStatus(OrderStatus.WAIT_RECEIVE.getStatus());
        orderEntity.setDvyTime(new Date());
        boolean b = orderService.updateOrder(orderEntity);
        if (!b) return ResultEntity.error(HttpCode.内部服务器错误.getCode(), "确认发货错误！");
        return ResultEntity.ok();
    }


    @GetMapping("/order/seller/inform-buyer")
    public ResultEntity sellerInformBuyer(@RequestParam("orderId") String orderId) {
        // 需要获取订单的信息 包括了卖家 和  买家的全部信息
        // 需要获取通知方  和  被通知方 同时需要信息  通知的信息 对象
        // TODO 通过队列来实现通知信息  但是需要ip 多次通知限制

        return ResultEntity.ok();
    }

    // 删除订单接口
    @PostMapping("/order/delete")
    public ResultEntity deleteOrderByOrderId(@RequestParam("orderId") String orderId) {
        boolean result = orderService.deleteOrderById(orderId);
        if (result) {
            return ResultEntity.ok();
        }
        return ResultEntity.error(HttpCode.内部服务器错误.getCode(),"删除失败！");
    }
}
